package cn.itcast.sailing.controller;
import cn.itcast.sailing.entity.Task;
import cn.itcast.sailing.entity.TaskLog;
import cn.itcast.sailing.job.SchedulerConfig;
import cn.itcast.sailing.service.TaskLogService;
import cn.itcast.sailing.service.TaskService;
import cn.itcast.sailing.util.Result;
import cn.itcast.sailing.wyy.api.MusicApi;
import cn.itcast.sailing.wyy.domain.entity.MusicUser;
import cn.itcast.sailing.wyy.util.ExceptionConstants;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Slf4j
@Api(value = "验证码服务接口")
@RestController
@RequiredArgsConstructor
public class DemoWebController {


    private final MusicApi api;
    private final TaskService taskService;
    private final TaskLogService taskLogService;


@PostMapping("/runJob")
public String runMusicJobWithParams(@RequestParam(name = "paramInput") String paramInput,
                                    @RequestParam(name = "nickname") String nickname){
    Task task = new Task();
    task.setToken(paramInput);
    task.setName(nickname);
    taskService.save(task);
    return "已保存";
}


    @GetMapping("/taskLog")
    public Result<IPage<TaskLog>> getTaskLog(@RequestParam(required = false) String name,
                                            @RequestParam(defaultValue = "1") Integer pageNo,
                                            @RequestParam(defaultValue = "10") Integer pageSize) {



        LambdaQueryWrapper<TaskLog> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.eq(TaskLog::getName, name);
        }
        wrapper.orderByDesc(TaskLog::getCreateTime);
        Page<TaskLog> page = new Page<>(pageNo, pageSize); // 创建分页对象
        IPage<TaskLog> resultPage = taskLogService.page(page, wrapper); // 使用分页查询

        return Result.success(resultPage);
    }




    public void listenSongsDaily(MusicUser user) {

            //因为每天上限是300首，但是要歌曲不重复，如果需要不重复的300首之后停止，请轮询用户等级信息接口获取听歌量后自行判断，successCount此处只能作为记录请求次数，无法确定是否成功刷歌
            int successCount = 0;
            int nowPlayCount = Integer.parseInt(api.userLevel(user.getCookie()).getJSONObject("data").getString("nowPlayCount"));
            int upperLimit = nowPlayCount + 300;
            log.info("每日听歌打卡=========================");
            //判断是否需要重试
            //首先获取可用的代理ip池
            //获取每日推荐歌单，保证是不影响听歌口味
            JSONObject resourceJSON = api.getRecommentSongs(user.getCookie());
            //解析歌单，返回一个map，key是歌单id,value是歌单中歌曲id的集合
            Map<Long, List<Long>> playListMap = api.parsePlayList(resourceJSON, user.getCookie());
            Set<Long> playListKeySet = playListMap.keySet();
            a:
            for (Long sourceId : playListKeySet) {
                List<Long> songIdList = playListMap.get(sourceId);
                for (Long songId : songIdList) {
                    try {
                        JSONObject listenResult = api.listenSong(user.getCookie(), String.valueOf(songId), String.valueOf(sourceId));
                        if (listenResult != null && listenResult.getInteger("code") == 200) {
                            successCount++;
                            log.info(user.getName() + ": 第" + successCount + "首 : " + "====>>歌单id:" + sourceId + "===>>歌曲ID : " + songId + "目标 ：" + upperLimit);
                            Thread.sleep(500);
                            //每100首检测一次
                            if (successCount >= 300 && successCount % 50 == 0) {
                                int t = Integer.parseInt(api.userLevel(user.getCookie()).getJSONObject("data").getString("nowPlayCount"));
                                if (t == upperLimit | successCount > 2000) {
                                    log.info("已完成每日300首听歌当前等级听歌量为：{}", t);
                                    break a;
                                }
                                log.info("当前听歌量为 : {}首,未达到目标 : {}首", t, upperLimit);
                            }
                        }
                    } catch (Exception e) {
                        log.info("失败");
                    }
                }
            }

    }


}
